package cn.ddiancan.auth.handler;

import java.io.IOException;

import cn.ddiancan.auth.service.converter.XddOAuth2ErrorHttpMessageConverter;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.oauth2.server.authorization.web.authentication.OAuth2ErrorAuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

public class XddAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) throws IOException, ServletException {
        OAuth2ErrorAuthenticationFailureHandler oAuth2ErrorAuthenticationFailureHandler =
            new OAuth2ErrorAuthenticationFailureHandler();
        response.setHeader(HttpHeaders.SET_COOKIE, "JSESSIONID=deleted; Path=/; HttpOnly; Secure; Max-Age=0 " +
            "EXPIRES=Thu, 01 Jan 1970 00:00:00 GMT; SameSite=None;login_flag=false");
        oAuth2ErrorAuthenticationFailureHandler.setErrorResponseConverter(new XddOAuth2ErrorHttpMessageConverter());
        oAuth2ErrorAuthenticationFailureHandler.onAuthenticationFailure(request, response, exception);
    }
}
